//
//  UserNotify.swift
//  studay
//
//  Created by APPLE on 2024/12/17.
//

import NotificationCenter

class UserNotification {
    
    
    init(){
        self.requestAuthorization({
            (success) in
            if(!success){
                self.openSetting()
            }
        })
    }
    
    func requestAuthorization (_ callback:@escaping (_ success:Bool)->Void){
        
       UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) {
           (status, err) in
            if !status {
                print("用户不同意授权通知权限")
               
                callback(false)
                return
            }
           
           callback(true)
           
        }
       

    }
    
    func openSetting(){
        DispatchQueue.main.async {
            guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
            if UIApplication.shared.canOpenURL(url) {
          
                UIApplication.shared.open(url, completionHandler: nil)
            }
        }
    }
    
    static func createNotificationContent(title:String,subtitle:String,body:String,badge:NSNumber)->UNMutableNotificationContent{
        let content = UNMutableNotificationContent()
        content.title = title
        content.subtitle = subtitle
        content.body = body
        content.badge = badge
        return content
    }
    
    func addNotification(identifier:String,content:UNMutableNotificationContent,timeInterval:Double){
        // 确保时间间隔大于0
       guard timeInterval > 0 else {
           print("通知时间间隔必须大于0秒")
           return
       }
        removeNotification(identifier: [identifier])
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) { err in
            err != nil ? print("添加本地通知错误", err!.localizedDescription) : print("添加本地通知成功")
        }

    }
    
    
    func removeNotification(identifier:[String]){
        UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifier)
        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifier)
    }
    
    
}
 
